<?php

/**
 * MyAccountController is the default controller for this application
 */
class MyAccountController extends BrowseControllerBase {
	/**
	 * UserDataService Object
	 *
	 * @var UserDataService object
	 */
	public $userDataService = null;
	
	/**
	 * PackageOrderDataService Object
	 *
	 * @var PackageOrderDataService object
	 */
	public $packageOrderDataService = null;
	
	/**
	 * SettingsDataService Object
	 *
	 * @var SettingsDataService object
	 */
	public $settingsDataService = null;
	
	/**
	 * TemplateCategoryDataService Object
	 *
	 * @var TemplateCategoryDataService object
	 */
	public $templateCategoryDataService = null;
	
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		
		$this->requireUserLogin ();
		
		// Init all Data Service
		$this->userDataService = new UserDataService ();
		$this->settingsDataService = new SettingsDataService ();
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing page of the site.
	 *
	 * @return void
	 *
	 */
	public function indexAction() {
		$arrElement = array ();
		$arrElement ['userId'] = $this->authentication->getCurrentUserId ();
		$arrElement ['paymentMethod'] = PAYMENT_PAYPAL;
		$arrElement ['status'] = PackageOrderEntity::COMPLETED;
		$items = $this->packageOrderDataService->getItems ( $arrElement, " createdDate DESC " );
		if (count ( $items ) == 0) {
			$this->smarty->assign ( 'isCancelled', true );
		}
		
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/MyAccount/user_panel.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/**
	 *
	 * Logout Action
	 */
	public function logoutAction() {
		$userDataService = new UserDataService ();
		// Logout
		$userDataService->logout ();
		// Redirect to homepage
		$url = Zend_Registry::get ( 'config' )->APPLICATION_URL;
		CommonUtils::redirect ( $url );
	}
	
	/**
	 *
	 * Update Website Settings and User Template
	 */
	public function settingsAction() {
		// Get All Settings data from DB
		$domainSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_DOMAIN, $this->authentication->getCurrentUserId () );
		$webNameSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_WEBSITE_NAME, $this->authentication->getCurrentUserId () );
		
		$webLogoSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_WEBSITE_LOGO, $this->authentication->getCurrentUserId () );
		$webFaviconSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_WEBSITE_FAVICON, $this->authentication->getCurrentUserId () );
		$facebookSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_FACEBOOk, $this->authentication->getCurrentUserId () );
		$twitterSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_TWITTER, $this->authentication->getCurrentUserId () );
		$linkinSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_LINKIN, $this->authentication->getCurrentUserId () );
		$dribbbleSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_DRIBBBLE, $this->authentication->getCurrentUserId () );
		$diggSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_DIGG, $this->authentication->getCurrentUserId () );
		$vimeoSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_VIMEO, $this->authentication->getCurrentUserId () );
		$youtubeSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_YOUTUBE, $this->authentication->getCurrentUserId () );
		$forrstSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_FORRST, $this->authentication->getCurrentUserId () );
		$flickrSettingsEntity = $this->settingsDataService->getItem ( SETTINGS_USER_FLICKR, $this->authentication->getCurrentUserId () );
		
		/*if(!$domainSettingsEntity)
		 {
			$domainSettingsEntity = $this->settingsDataService->addSetting(SETTINGS_USER_DOMAIN, $this->authentication->getCurrentUserId());
			}
			if(!$webNameSettingsEntity)
			{
			$webNameSettingsEntity = $this->settingsDataService->addSetting(SETTINGS_USER_WEBSITE_NAME, $this->authentication->getCurrentUserId());
			}

			if(!$webLogoSettingsEntity)
			{
			$webLogoSettingsEntity = $this->settingsDataService->addSetting(SETTINGS_USER_WEBSITE_LOGO, $this->authentication->getCurrentUserId());
			}

			if(!$webFaviconSettingsEntity)
			{
			$webFaviconSettingsEntity = $this->settingsDataService->addSetting(SETTINGS_USER_WEBSITE_FAVICON, $this->authentication->getCurrentUserId());
			}

			if(!$facebookSettingsEntity)
			{
			$facebookSettingsEntity = $this->settingsDataService->addSetting(SETTINGS_USER_FACEBOOk, $this->authentication->getCurrentUserId());
			}

			if(!$twitterSettingsEntity)
			{
			$twitterSettingsEntity = $this->settingsDataService->addSetting(SETTINGS_USER_TWITTER, $this->authentication->getCurrentUserId());
			}

			if(!$linkinSettingsEntity)
			{
			$linkinSettingsEntity = $this->settingsDataService->addSetting(SETTINGS_USER_LINKIN, $this->authentication->getCurrentUserId());
			}
			*/
		
		// Get action method and check it
		$actionForm = $this->getPost ( 'actionForm', '' );
		$errorInfoMessage = array ();
		
		// Only Normal User or Admin User can update this information
		if (! empty ( $actionForm ) && $actionForm == 'submit' && $this->isDemoMode == false) {
			
			// Get Email field
			$url = $this->getPost ( 'url', "" );
			$url = trim ( $url );
			
			if ((preg_match ( '/^([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url )) || empty ( $url )) {
				// Get name field
				$name = $this->getPost ( 'name', "" );
				$name = trim ( $name );
				
				// Check if domain has www string
				$pos = strpos ( $url, "www." );
				if ($pos === false && ! empty ( $url )) {
					// Add www. as prefix
					$url = "www." . $url;
				}
				/*
				 else {

					$url = substr($url, $pos + 4, strlen($url));
					}
					*/
				
				if ($url != $domainSettingsEntity->value && $this->settingsDataService->checkExistUserDomain ( $domainSettingsEntity->value ) == 1) {
					$errorInfoMessage [] = "Invalid Domain. Domain is had exist !";
				} else {
					$domainSettingsEntity->value = $url;
					$this->settingsDataService->update ( $domainSettingsEntity );
				}
				
				$webNameSettingsEntity->value = $name;
				$this->settingsDataService->update ( $webNameSettingsEntity );
				
				// Update Configuration for Plesk Parallel
				$this->reconfigurePlesk ( $url );
			} else if ($url != "") {
				$errorInfoMessage [] = "Invalid Domain. Please try http://yourdomainname.com";
			}
			
			// Upload Logo and favicon file
			$website_logo = '';
			try {
				$website_logo = CommonUtils::uploadPicture ( 'website-logo' );
				if ($website_logo != "") {
					$webLogoSettingsEntity->value = $website_logo;
					$this->settingsDataService->update ( $webLogoSettingsEntity );
				}
			} catch ( Exception $ex ) {
				$errorInfoMessage [] = "Website Logo file is invalid (only image files are supported). Please try again";
			}
			
			$website_favicon = '';
			try {
				$website_favicon = CommonUtils::uploadFavicon ( 'website-favicon' );
				if ($website_favicon != "") {
					$webFaviconSettingsEntity->value = $website_favicon;
					$this->settingsDataService->update ( $webFaviconSettingsEntity );
				}
			} catch ( Exception $ex ) {
				$errorInfoMessage [] = "Website Favicon file is invalid (Only png or ico file is supported). Please try again";
			}
			
			// Update FB, TW , Linkin , Dribbble, Digg, Vimeo, Youtube, forrst and  flickr link
			$facebook = $this->getPost ( 'facebook', "" );
			$facebook = trim ( $facebook );
			$twitter = $this->getPost ( 'twitter', "" );
			$twitter = trim ( $twitter );
			$linkin = $this->getPost ( 'linkin', "" );
			$linkin = trim ( $linkin );
			$dribbble = $this->getPost ( 'dribbble', "" );
			$dribbble = trim ( $dribbble );
			$digg = $this->getPost ( 'digg', "" );
			$digg = trim ( $digg );
			$vimeo = $this->getPost ( 'vimeo', "" );
			$vimeo = trim ( $vimeo );
			$youtube = $this->getPost ( 'youtube', "" );
			$youtube = trim ( $youtube );
			$forrst = $this->getPost ( 'forrst', "" );
			$forrst = trim ( $forrst );
			$flickr = $this->getPost ( 'flickr', "" );
			$flickr = trim ( $flickr );
			
			if ((preg_match ( '/^(http):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $facebook )) && $facebook != "") {
				$facebookSettingsEntity->value = $facebook;
				
				$this->settingsDataService->update ( $facebookSettingsEntity );
			} else if ($facebook != "") {
				$errorInfoMessage [] = "Invalid Facebook URL";
			}
			
			if ((preg_match ( '/^(http):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $twitter ))) {
				$twitterSettingsEntity->value = $twitter;
				$this->settingsDataService->update ( $twitterSettingsEntity );
			} else if ($twitter != "") {
				$errorInfoMessage [] = "Invalid Twitter URL";
			}
			
			if ((preg_match ( '/^(http):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $linkin )) && $linkin != "") {
				$linkinSettingsEntity->value = $linkin;
				$this->settingsDataService->update ( $linkinSettingsEntity );
			} else if ($linkin != "") {
				$errorInfoMessage [] = "Invalid Linkin URL";
			}
			
			if ((preg_match ( '/^(http):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $dribbble )) && $dribbble != "") {
				$dribbbleSettingsEntity->value = $dribbble;
				$this->settingsDataService->update ( $dribbbleSettingsEntity );
			} else if ($dribbble != "") {
				$errorInfoMessage [] = "Invalid Dribbble URL";
			}
			
			if ((preg_match ( '/^(http):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $digg )) && $digg != "") {
				$diggSettingsEntity->value = $digg;
				$this->settingsDataService->update ( $diggSettingsEntity );
			} else if ($digg != "") {
				$errorInfoMessage [] = "Invalid Digg URL";
			}
			
			if ((preg_match ( '/^(http):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $vimeo )) && $vimeo != "") {
				$vimeoSettingsEntity->value = $vimeo;
				$this->settingsDataService->update ( $vimeoSettingsEntity );
			} else if ($vimeo != "") {
				$errorInfoMessage [] = "Invalid Vimeo URL";
			}
			
			if ((preg_match ( '/^(http):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $youtube )) && $youtube != "") {
				$youtubeSettingsEntity->value = $youtube;
				$this->settingsDataService->update ( $youtubeSettingsEntity );
			} else if ($youtube != "") {
				$errorInfoMessage [] = "Invalid Youtube URL";
			}
			
			if ((preg_match ( '/^(http):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $forrst )) && $forrst != "") {
				$forrstSettingsEntity->value = $forrst;
				$this->settingsDataService->update ( $forrstSettingsEntity );
			} else if ($forrst != "") {
				$errorInfoMessage [] = "Invalid Forrst URL";
			}
			
			if ((preg_match ( '/^(http):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $flickr )) && $flickr != "") {
				$flickrSettingsEntity->value = $flickr;
				$this->settingsDataService->update ( $flickrSettingsEntity );
			} else if ($flickr != "") {
				$errorInfoMessage [] = "Invalid Flickr URL";
			}
			
			// Update User Template
			$templates = $this->getPost ( 'templates', '' );
			if ($templates != "") {
				$currentUser = $this->userDataService->getById ( $this->authentication->getCurrentUserId () );
				$currentUser->mainTemplateId = $templates;
				$this->userDataService->update ( $currentUser );
			}
		}
		
		// Get List of TemplateCategory
		$arrElement = array ();
		$catList = $this->templateCategoryDataService->getItems ( $arrElement );
		$this->smarty->assign ( 'catList', $catList );
		
		// Current Template ID
		$currentUser = $this->userDataService->getById ( $this->authentication->getCurrentUserId () );
		
		$this->smarty->assign ( 'currentTemplateId', $currentUser->mainTemplateId );
		
		// Get List Of Ready Templates
		$logoUrl = ($webLogoSettingsEntity->value != "") ? Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Resources/Images/' . $webLogoSettingsEntity->value : "";
		$faviconUrl = ($webFaviconSettingsEntity->value) ? Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Resources/Images/' . $webFaviconSettingsEntity->value : "";
		$this->smarty->assign ( 'errorInfoMessage', $errorInfoMessage );
		$this->smarty->assign ( 'url', $domainSettingsEntity->value );
		$this->smarty->assign ( 'name', $webNameSettingsEntity->value );
		$this->smarty->assign ( 'website_logo', $logoUrl );
		$this->smarty->assign ( 'website_favicon', $faviconUrl );
		$this->smarty->assign ( 'facebook', $facebookSettingsEntity->value );
		$this->smarty->assign ( 'twitter', $twitterSettingsEntity->value );
		$this->smarty->assign ( 'linkin', $linkinSettingsEntity->value );
		$this->smarty->assign ( 'dribbble', $dribbbleSettingsEntity->value );
		$this->smarty->assign ( 'digg', $diggSettingsEntity->value );
		$this->smarty->assign ( 'vimeo', $vimeoSettingsEntity->value );
		$this->smarty->assign ( 'youtube', $youtubeSettingsEntity->value );
		$this->smarty->assign ( 'forrst', $forrstSettingsEntity->value );
		$this->smarty->assign ( 'flickr', $flickrSettingsEntity->value );
		
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/MyAccount/user_web_info.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/*
	 * Update user gereral information
	 */
	public function editAction() {
		//Get Current User information
		$authentication = new Authentication ();
		$actionForm = $this->getPost ( 'actionForm', '' );
		
		// Only Normal User or Admin User can update this information
		if (! empty ( $actionForm ) && $actionForm == 'submit' && $this->isDemoMode == false) {
			$firstName = $this->getPost ( 'firstName', '' );
			$lastName = $this->getPost ( 'lastName', '' );
			$city = $this->getPost ( 'town', '' );
			$address = $this->getPost ( 'address', '' );
			$telephone = $this->getPost ( 'number', '' );
			$house = $this->getPost ( 'hnumber', '' );
			$birthday = $this->getPost ( 'birthday', '' );
			$email = $this->getPost ( 'email', '' );
			$zipCode = $this->getPost ( 'postcode', '' );
			$countryId = $this->getPost ( 'country', '' );
			$userEntity = $this->userDataService->getById ( $authentication->getCurrentUserId () );
			$userEntity->firstName = $firstName;
			$userEntity->lastName = $lastName;
			$userEntity->countryId = $countryId;
			$userEntity->city = $city;
			$userEntity->address = $address;
			$userEntity->telephone = $telephone;
			$userEntity->email = $email;
			$userEntity->house = $house;
			$userEntity->birthday = $birthday;
			$userEntity->zipCode = $zipCode;
			
			$res = $this->userDataService->update ( $userEntity );
		}
		
		$userEntity = $this->userDataService->getById ( $authentication->getCurrentUserId () );
		$this->smarty->assign ( 'userEntity', $userEntity );
		if (isset ( $userEntity )) {
			$firstName = $userEntity->firstName;
			$lastName = $userEntity->lastName;
			$country = $userEntity->countryId;
			$city = $userEntity->city;
			$address = $userEntity->address;
			$telephone = $userEntity->telephone;
			$house = $userEntity->house;
			$email = $userEntity->email;
			$town = $userEntity->city;
			$zipCode = $userEntity->zipCode;
			$birthday = $userEntity->birthday;
			
			$this->smarty->assign ( 'firstName', $firstName );
			$this->smarty->assign ( 'lastName', $lastName );
			$this->smarty->assign ( 'country', $country );
			$this->smarty->assign ( 'city', $city );
			$this->smarty->assign ( 'address', $address );
			$this->smarty->assign ( 'email', $email );
			$this->smarty->assign ( 'telephone', $telephone );
			$this->smarty->assign ( 'house', $house );
			$this->smarty->assign ( 'town', $town );
			$this->smarty->assign ( 'zipCode', $zipCode );
			$this->smarty->assign ( 'birthday', $birthday );
		
		} else {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/MyAccount/user_profile.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/**
	 * Upgrade Action Handling
	 */
	public function upgradeAction() {
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/MyAccount/user_profile.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/**
	 * Home Page Action Handling
	 */
	public function homepageAction() {
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/MyAccount/user_panel.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/**
	 * Reconfigure Plesk for all domain
	 */
	private function reconfigurePlesk($name) {
		//Write the name to vhost file
		$settingsDataService = new SettingsDataService ();
		$win = stripos ( PHP_OS, 'win' ) !== false ? true : false;
		if ($win == false) {
			$settingsDataService->exportVhostFile ();
		}
	}
	
	/**
	 * Write Output to Log file
	 * @param array $output
	 */
	private function writeOutput($output) {
		$str = "";
		foreach ( $output as $item ) {
			$str .= $item . "\r\n";
		}
		
		$this->logger->log ( $str, Zend_Log::DEBUG );
	}
}
